﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace DAO
{
    class ConnectData
    {
        private SqlConnection conn;
        private SqlDataAdapter dataAp;
        private DataTable dataTable;

        //Ham dung mac dinh khi goi ket noi
        public ConnectData()
        {
            Connect();
        }

        //Ket noi
        public void Connect()
        {
            string strConn = @"Data Source=THANHTHOAI-PC;Integrated Security=SSPI;Initial Catalog = QuanLyNhaSach";
            try
            {
                conn = new SqlConnection(strConn);
                conn.Open();
                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }

        //Select Data
        public DataTable GetDataTable(string sql)
        {
            //Thuc hien lenh query truyen vao
            dataAp = new SqlDataAdapter(sql, conn);
            //Do du lieu vao DataTable
            dataTable = new DataTable();
            dataAp.Fill(dataTable);
            return dataTable;
        }

        //Thuc hien I, U, D: tra ve thanh cong hay that bai
        public bool ExecuteQuery(string sql)
        {
            int numRecords = 0;
            try
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                numRecords = cmd.ExecuteNonQuery();
                if (conn.State == ConnectionState.Open)
                    conn.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
            if (numRecords > 0)
                return true;
            return false;
        }

        //Ham lay ma cuoi cung trong CSDL
        public string GetLastID(string nameTable, string nameField)
        {
            string sql = "Select top 1 " + nameField + "From " + nameTable + "Order by" + nameField + "Desc";
            //Thuc hien cau  truy van
            GetDataTable(sql);
            return dataTable.Rows[0][nameField].ToString();
        }

        //Kiem tra xem du lieu co ton tai hay ko
        public bool CheckExitstValue(string nameTable, string nameField, string value)
        {
            string sql = "SELECT * FROM " + nameTable + " WHERE " + nameField + " = '" + value + "'";
            GetDataTable(sql);
            // Đếm số dòng trả về, nếu > 0  tức tồn tại value
            if (dataTable.Rows.Count > 0)
                return true;
            return false;
        }
    }
}
